<template>
  <div class="product_plan">
    <el-dialog
      :title="title"
      :width="device === 'mobile'? '700px' :'80%'"
      :visible.sync="dialogShow"
      :before-close="handleClose"
      :modal="!addPlanShow"
      :close-on-click-modal="!addPlanShow"
    >
      <el-form :model="form" :rules="rules" label-width="140px" ref="formRef" style="width: 100%;height: 78vh;">
        <!-- 城市变价相关信息 -->
        <template >
           <!-- 城市变价公共区域 -->
           <div class="upAndDownLinesPublic" 
             style="
             border-bottom: 1px solid #dfe6ec;
             margin-bottom: 10px;
             padding-bottom:10px;
             display: flex">
             <div v-for="item in productPlanShowOption" :key="item.prop" style="margin-right: 20px;display: flex;align-items: center;">
                <span style="margin-right: 5px;"><span>{{ item.label }}:</span></span>
                <span v-if="item.prop === 'statusStr'">
                  <el-tag :type="statusColor(productObj.status)">{{  productObj[item.prop] }}</el-tag>
                </span>
                <span v-else>
                  <span style="font-weight: 600;">{{  productObj[item.prop] }}</span>
                </span>
            </div>
           </div>
           <!--城市变价管理特殊区域特殊区域 -->
           <div style="width: 100%;height: calc(100% - 40px);">
              <div style="padding:0 0 10px;" >
                【城市变价】价格控制
              </div>
              <div style="display: flex;width: 100%;height: calc(100% - 28px);">
                  <div style="margin-right: 10px;width: 66px;" >
                    <el-button
                      type="text"
                      @click="addPlan()"
                      style="text-decoration: underline;"
                     >
                     +添加一条
                     </el-button
                    >
                  </div>
                  <!-- 表格区域 -->
                  <div class="TaskTable" style="flex: 1;width: calc(100% - 76px);height: 100%;display: flex;flex-direction: column;">
                    <div ref="TaskSearchBox" class="flex">
                       <el-form
                         :model="productPlanQeryParams"
                         ref="productPlanQeryParams"
                         :inline="true"
                         label-width="100px"
                       >
                        <el-form-item label="省编码集合" prop="provinceCodes">
                          <el-select
                           v-model="productPlanQeryParams.provinceCodes"
                           multiple
                           collapse-tags
                           clearable
                           filterable
                           placeholder="请选择"
                           style="width: 250px; margin-right: 10px"
                          >
                            <el-option
                             v-for="(item, index) in provinceCodeOption"
                             :key="index"
                             :label="item.name"
                             :value="item.code"
                             ></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="城市编码集合" prop="cityCodes">
                         <el-select
                          v-model="productPlanQeryParams.cityCodes"
                          multiple
                          collapse-tags
                          clearable
                          filterable
                          placeholder="请选择"
                          style="width: 250px; margin-right: 1px"
                         >
                           <el-option
                            v-for="(item, index) in cityCodeOption"
                            :key="index"
                            :label="item.name"
                            :value="item.code"
                            ></el-option>
                         </el-select>
                        </el-form-item>
                        <el-form-item>
                           <el-button
                             type="primary"
                             icon="el-icon-search"
                             size="mini"
                             @click="productPlanHandleQuery"
                             plain
                             >查询</el-button
                           >
                           <el-button
                             icon="el-icon-refresh"
                             size="mini"
                             @click="productPlanResetQuery"
                             >重置</el-button
                           >
                         </el-form-item>
                       </el-form>
                   </div>
                   <div :style="{
                      width: '100%',
                      height: `calc(100% - ${$refs.TaskSearchBox && $refs.TaskSearchBox.offsetHeight}px)`,
                      overflowY:'auto',
                      paddingBottom:'15px'
                    }">
                    <el-table
                      v-loading="loading"
                      :data="dataList"
                      border
                      v-sticky-header="{offsetTop: '0px'}"
                      >
                        <el-table-column
                          v-for="(upAnditem,upAndindex) in columns"
                          :key="upAndindex"
                          :prop="upAnditem.prop"
                          :label="upAnditem.label"
                          :width="getColumnWidth(upAndindex,'columns')"
                          show-overflow-tooltip
                          align="center"
                        >
                          <template slot-scope="upAndScope">
                            <span>
                             {{  upAndScope.row[upAnditem.prop] }}
                            </span>
                          </template>
                        </el-table-column>
                        <el-table-column
                          fixed="right"
                          align="center"
                          label="操作"
                          width="100"
                        >
                        <template slot-scope="addPlanScope">
                          <div class="flex-center">
                            <el-button 
                              style="color: #0050b3;" 
                              type="text" size="small" 
                              @click="editaddPlan(addPlanScope.row)"
                              >
                              编辑
                            </el-button>
                            <el-popconfirm
                             title="确定要删除该变价吗？"
                             style="margin-left: 10px"
                             @cancel="hanCancelDel"
                             @confirm="deladdPlan(addPlanScope.row)"
                            >
                              <el-button 
                                slot="reference"
                                style="color: #ff116e;" 
                                type="text" size="small" 
                                >
                                删除
                              </el-button>
                            </el-popconfirm>
                          </div>
                           
                        </template>
                       </el-table-column>
                    </el-table>
                    <!-- 使用分页插件 -->
                    <pagination
                     v-show="total > 0"
                     :total="total"
                     :page-sizes="[10, 20, 50, 100]"
                     :page.sync="productPlanQeryParams.pageIndex"
                     :limit.sync="productPlanQeryParams.pageSize"
                     @pagination="getProductPlanList"
                    />
                  </div>
                  </div>
              </div>
           </div>
        </template>
      </el-form>
      <!-- 城市变价添加变价对话框 -->
      <el-dialog
         :title="addPiceTitle"
         width="600px"
         :visible.sync="addPlanShow"
         :before-close="closeaddPlan"
         :modal="false"
         :close-on-click-modal="false"
        >
        <el-form :model="addPriceForm" :rules="addPriceRules" ref="addPriceFormRef" label-width="90px">
           <el-form-item label="省市" prop="provinceOrcity">
              <el-cascader
                filterable
                v-model="addPriceForm.provinceOrcity"
                v-removeAriaHidden
                :options="addressTree"
                :props="{
                  value: 'code',
                  label: 'name',
                  children: 'list',
                  emitPath: true,
                  checkStrictly: false,
                }"
                clearable
                placeholder="请选择省市"
                style="width: 100%"
              ></el-cascader>
          </el-form-item>
           <el-form-item 
            label="渠道价格" 
            prop="upPriceMoney"
          >
            <el-input-number 
              v-model="addPriceForm.upPriceMoney" 
              controls-position="right" 
              placeholder="请输入"
              :precision="2"
              :min="0" 
              style="width: 100%;"
            >
            </el-input-number>
          </el-form-item>
         
        
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addPlanHandleSubmit('addPriceFormRef')">保存</el-button>
          <el-button @click="closeaddPlan">取 消</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  addOrEditCity,
  deleteCityById,
  queryCityById,
  queryProductCityByPage,
} from "@/api/business/channelManagement";
import {getAreaCodeList,getAreaCodeTreeList} from '@/api/system/areaCode'
export default {
  name: 'cityUpdPrice',
  data() {
    return {
      // 弹框标题
      title: "城市变价面板",
      // 弹框显示状态
      dialogShow: false,
      // 弹框的表单信息
      form: {},
      // 弹框表单校验规则
      rules: {
      },
      
      // 城市变价添加变价弹框显示状态
      addPlanShow: false,
       // 城市变价总条数
      total: 0,
      // 城市变价查询参数
      productPlanQeryParams: {
        pageIndex: 1,
        pageSize: 10,
      },
      // 城市列表筛选项
      cityCodeOption:[],
      // 省份列表筛选项
      provinceCodeOption:[],


      // 城市变价表格加载状态
      loading: false,
      // 城市变价任务表格数据
      dataList:[],
      // 城市变价任务表格列信息
      columns:[
        {label: `渠道名`,prop: "productName",pcWidth: 220,mobileWidth: 150,},
        {label: `省名称`,prop: "provinceName",pcWidth: 180,mobileWidth: 120,},
        {label: `城市名称`,prop: "cityName",pcWidth: 180,mobileWidth: 120,},
        {label: `渠道模式`,prop: "upRewardTypeStr",pcWidth: 180,mobileWidth: 120,},
        {label: `渠道价格`,prop: "upRewardStr",pcWidth: 150,mobileWidth: 120,},
        {label: `操作人`,prop: "updateUserName",pcWidth: 150,mobileWidth: 100,},
        {label: `操作时间`,prop: "updateTime",pcWidth: 220,mobileWidth: 180,},
      ],
      // 城市变价展示筛选项
      productPlanShowOption:[
        { label: "渠道名称", prop: 'productName' },
        { label: "关联公司", prop: 'companyName' },
        { label: "渠道状态", prop: 'statusStr' },
      ],
      // 渠道信息对象
      productObj:{},

      // 添加变价弹框标题
      addPiceTitle: "",
      // 添加变价弹框的表单信息
      addPriceForm: {},
      // 添加变价弹框的校验规则
      addPriceRules: {
        
      },
      // 地址级联数据
      addressTree:[],
      // 全国省市区对象形式:{code:name}形式
      areaObj:{},
    };
  },
  computed: {
    ...mapGetters(["sidebar", "device"]),
    // 对状态进行处理
    statusColor:()=>{
        return (state)=>{
           switch(state){
             case 0:
                return 'success';
             case 1:
                return 'info';
             case 2: 
                return 'danger';
             case 3:
                return 'warning';
             default:
           }
        }
    },
    // 计算当前列元素在所处环境的宽度
    getColumnWidth() {
      return (index,columName) => {
          return this.device == 'mobile'
          ? this[columName][index].mobileWidth
          : null;
      };
    },
  },
  methods: {
    // 扁平化全国省市地址为对象形式
    flattenAreaObj(data) {
        return data.reduce((obj,pre)=>{
          // 如果存在子节点
          if(pre?.list){
            obj[pre.code] = pre.name
            obj =Object.assign({},obj,this.flattenAreaObj(pre.list))
          }else{
            obj = {...obj,...{[pre.code]:pre.name}}
          }
          return obj
        },{})
    },
    // 获取全国城市、省份列表
    getCityOrProvinceCodeList(){
      getAreaCodeList(2).then(res=>{
        this.cityCodeOption = res.data
      })
      getAreaCodeList(1).then(res=>{
        this.provinceCodeOption = res.data
      })
      // 获取级联数据
      getAreaCodeTreeList().then(res=>{
          this.addressTree = res.data
          this.areaObj = this.flattenAreaObj(res?.data);
      })
    },
    // 打开城市变价对话框
    openHandle(data){
       // 打开城市变价对话框
       this.dialogShow = true
       // 设置渠道信息对象
       this.$set(this,'productObj',data)
       // 获取城市、省份列表
       this.getCityOrProvinceCodeList()
       // 获取城市变价列表
       this.productPlanHandleQuery()
    },
     /*关闭弹窗*/
    handleClose(){
      this.$refs['formRef'].resetFields();
      this.form = this.$options.data().form;
      this.dialogShow = false;
      
    },
    /** 查询城市变价列表 */
    getProductPlanList() {
      this.loading = true;
      queryProductCityByPage({
        ...this?.productPlanQeryParams,
        productId: this.productObj?.id,
      }).then((response) => {
        this.dataList = response?.data?.list;
        this.total = response?.data?.total;
        this.loading = false;
      }).catch((err) => {
        setTimeout(() => {// 延迟2s后自动取消加载状态
          this.loading = false;
        }, 2000);
      })
    },
     /** 城市变价任务按钮操作 */
    productPlanHandleQuery() {
      this.$set(this.productPlanQeryParams, "pageIndex", 1);
      this.getProductPlanList();
    },
    /** 城市变价任务重置按钮操作 */
    productPlanResetQuery() {
      // 完全重置到初始状态
      this.$set(this, "productPlanQeryParams", {
        pageIndex: 1,
        pageSize: 10,
      });
      this.getProductPlanList();
    },
    // 城市变价添加变价打开弹框
    addPlan(){
      this.addPlanShow = true
      this.addPiceTitle = '添加变价'
    },
    // 渠道添加变价编辑操作
    editaddPlan(row){
      this.addPlanShow = true
      this.addPiceTitle = '编辑变价'
      // 通过详情接口获取详细数据
      queryCityById(row?.id).then((response) => {
        // 获取详细数据
        let data = response?.data;
        // 设置回显数据
        this.$set(this,'addPriceForm',data)
        // 设置回显的省市
        this.$set(this.addPriceForm,'provinceOrcity',[
          data?.provinceCode,
          data?.cityCode
        ])
      });
    },
     // 关闭添加变价弹窗
    closeaddPlan(){
      this.$refs['addPriceFormRef'] && this.$refs['addPriceFormRef'].resetFields();
      this.addPriceForm = this.$options.data().form;
      this.addPlanShow = false
    },
     /*添加变价提交操作*/
    addPlanHandleSubmit(formName){
       this.$refs[formName].validate((valid) => {
        if (valid) {
          let params={};
          params = JSON.parse(JSON.stringify({
            ...this?.addPriceForm,
            // 设置渠道id
            productId:this.productObj?.id
          }))
          let [provinceCode, cityCode] = params?.provinceOrcity
          params.provinceName = this.areaObj[provinceCode];
          params.cityName = this.areaObj[cityCode];
          params = {...params,provinceCode, cityCode}
          // console.log("参数",params);
          addOrEditCity(params).then(res=>{
            if(res.code === 200) {
              this.$message.success('操作成功')
              this.closeaddPlan()
              this.productPlanHandleQuery()
            }else{
              this.$message.error(res?.msg)
            }
          })

        }
      })
    },
    // 取消删除
    hanCancelDel(){
      this.$message({
        type: 'info',
        message: '已取消删除操作'
      });
    },
    // 删除列表项
    deladdPlan(row) {
      let { id } = row
      deleteCityById(id).then(res=>{
        if(res.code === 200) {
          this.$message.success('删除成功')
          this.productPlanHandleQuery()
        }
      })
    },
  }
};
</script>

<style scoped lang='scss'>
.el-table {
  // 滚动条加粗
  --scrollbar-height: 9px;
}
.TaskTable{
  ::v-deep ::-webkit-scrollbar {
    width: 8px; // 横向滚动条
    height: 8px; // 纵向滚动条
  }
  ::v-deep .el-table__header-wrapper {
    // overflow: visible !important; // 表头此时不会随着body左右滚动了
    height: 55px !important;  // 这个方案更推荐！！！
  }
}
</style>